# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from . import (
    api,
    db_conn
)

from flask import (
    request,
)

try:
    import json
except ImportError:
    import simplejson as json

try:
    from urllib.parse import unquote
except ImportError:
    from urllib import unquote

from ..dbhelper.article import Article


__all__ = []

@api.route(r'/article/', methods=['POST'])
def add_article():
    _title = request.values.get('title', None)
    _title = unquote(_title)
    _content = request.values.get('content', None)
    _content = unquote(_content)
    _summary = request.values.get('summary', None)
    _summary = unquote(_summary)
    obj = Article()
    db_result = obj.add(_title, _content, _summary)
    result = {
        'db': db_result
    }
    return json.dumps(result)

@api.route(r'/article/<regex("([0-9a-f]{4}([0-9a-f]{4}-){4}[0-9a-f]{12})?"):_id>', methods=['GET'])
def query_article(_id=None):
    if not bool(_id):
        _id = request.values.get('id', None)
    obj = Article()
    db_result = obj.query(_id)
    # _content = request.values.get('content', None)
    # count = query.count().run(conn)
    result = {
        'db': db_result
    }
    return  json.dumps(result)

@api.route(r'/article/<regex("([0-9a-f]{4}([0-9a-f]{4}-){4}[0-9a-f]{12})?"):_id>', methods=['PUT'])
def update_article(_id=None):
    if not bool(_id):
        _id = request.values.get('id', None)
    _title = request.values.get('title', None)
    _title = unquote(_title)
    _content = request.values.get('content', None)
    _content = unquote(_content)
    _summary = request.values.get('summary', None)
    _summary = unquote(_summary)
    obj = Article()
    db_result = obj.update(_id, _title, _content, _summary)
    result = {
        'db': db_result
    }
    return json.dumps(result)